package user;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.DataBaseServlet;
import device.DeviceFactory;

import ulti.tuple.Pair;

/**
 * Servlet implementation class SwitchDevice
 * 处理用户开关设备请求
 */
@WebServlet("/SwitchDevice")
public class SwitchDevice extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SwitchDevice() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		final String DEFAULT = "{\"suc\":%b, \"deviceId\":%d,\"msg\":\"%s\"}";
		//final String BROADCAST = "{\"target\":\"device\",\"device\":[{\"deviceId\":%d,\"power\":%b}]}";
		
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		int deviceId = 0;
		try
		{
			deviceId = Integer.parseInt(request.getParameter("deviceId"));
		}
		catch (NumberFormatException e)
		{
			System.out.println("无效的设备Id");
			out.write(String.format(DEFAULT,false, -1,"无效的参数"));
			return;
		}
		
		
		DataBaseServlet db = DataBaseServlet.DB; // 数据库
		
		Pair<Boolean, Boolean> res = db.queryPower(deviceId);
		if(res.first) {
			out.write(String.format(DEFAULT,true, deviceId,"ok"));
			
			DeviceFactory.switchPower(deviceId, !res.second);
			
		}else {
			out.write(String.format(DEFAULT,false, deviceId,"操作失败"));
		}
	}

}
